package com.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.service.iter.IZfbService;
import com.util.AlipayQRCodePayment;
import com.util.Res;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author Dumeng
 * @description TODO
 * @date 2023/6/22 23:41
 */
@Service
@Transactional
public class ZfbServiceImpl implements IZfbService {
    @Override
    public Res payOrder(String outTradeNo, BigDecimal totalPrice) {
        if (totalPrice.equals(BigDecimal.ZERO)) {
            throw new IllegalArgumentException("支付金额不得为0");
        }
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setTotalAmount(totalPrice.toString());
        model.setOutTradeNo(outTradeNo);
        model.setSubject("森饰家具订单");
        try {
            String response = AlipayQRCodePayment.payOrder(model);
            return new Res(response, 200, "等待支付");
        } catch (AlipayApiException e) {
            throw new RuntimeException("支付宝请求异常：" + e.getMessage());
        }
    }

    @Override
    public Res queryOrder(String outTradeNo) {
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(outTradeNo);
        try {
            AlipayTradeQueryResponse response = AlipayQRCodePayment.queryOrder(model);
            String subCode = response.getSubCode();
            if (subCode != null) {
                switch (subCode) {
                    case "ACQ.TRADE_NOT_EXIST":
                        return new Res(null, 202, "交易不存在");
                    case "ACQ.ACQ.SYSTEM_ERROR":
                        return new Res(null, 202, "系统错误");
                    case "ACQ.INVALID_PARAMETER":
                        return new Res(null, 202, "参数无效");
                }
            }
            switch (response.getTradeStatus()) {
                case "TRADE_SUCCESS":
                    return new Res(null, 200, "交易成功");
                case "WAIT_BUYER_PAY":
                    return new Res(null, 202, "等待支付");
                case "TRADE_CLOSED":
                    return new Res(null, 202, "交易关闭");
                case "TRADE_FINISHED":
                    return new Res(null, 202, "交易结束");
                default:
                    return new Res(null, 202, "发生错误");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException("交易查询请求异常：" + e.getMessage());
        }
    }
}
